var express = require('express');
var router = express.Router();
var Manager = require('../modules/mongo');
var DBManager =new Manager();
var async = require('async');

router.post('/addbookType', function(req, res, next){
    //头部内容req.headers
    let req_data = req.body
    let params = {
        bookType: req_data.bookType,
        create_time: new Date(),
        update_time: new Date()
    }
    async.waterfall([
        function (cb) {
            DBManager.findOne('booksType',{bookType: params.bookType},result => {
                console.log(result)
                if(result.success){
                    cb(null, true)
                    return
                }
                cb(null, false)
            })
        },
        function (n, cb){
            if(n){
                cb('该种书类型已存在')
                return
            }
            DBManager.insert('booksType', params, result => {
                if(result.success){
                    res.send({success:true, code: 0, message:'新增图书类型成功'})
                    return 
                }
                res.send({success:false, code: 1, message:'新增图书类型失败'})
            })
        }], 
        function(err,result){
            res.send({success:false, code: 1, message:'该种书类型已存在'})
    })
})

router.get('/', function(req, res, next){
    let req_data = req.query
    let params = {
        bookType: {$regex: req_data.bookType||'', $options: 'i' }
    }
    DBManager.find('booksType', params, {}, result => {
        if(result.success){
            res.send(result)
            return
        }
        res.send(result)
    })
})

router.post('/updatebookType', function(req, res, next){
    let req_data = req.body
    let whereData = {
        _id: req_data._id
    }
    let params = {
        bookType: req_data.bookType,
        update_time: new Date()
    }
    DBManager.update('booksType', whereData, {$set: params})
    .then(respone => {
        console.log(respone)
        if(respone.success){
            res.send({success:true, code: 0, message:'更新完成'})
        }
    }).catch(err => {
        res.send({success:true, result: err, message:'更新失败'})
    })
})

router.post('/deletebookType', function(req, res, next){
    let req_data = req.body
    DBManager.delete('booksType', {_id: req_data._id})
    .then(respone => {
        if(respone.success){
            res.send({success:true, code: 0, message:'删除成功'})
        }
    }).catch(err => {
        res.send({success:true, result: err, message:'删除成功'})
    })
})

module.exports = router;